import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import App from '../App'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: App,
    children: [
      {
        path: '',
        redirect: '/home'
      },
      { //城市选择页
        path: '/home',
        name: 'home',
        component: () => import('../views/home/home.vue')
      },
      //当前选择城市页
      {
        path: '/city/:cityid',
        name: 'city',
        component: () => import('../views/city/city.vue')
      },
      {
        //底部导航
        path: '/tabbar',
        name: 'tabbar',
        redirect: '/msite',
        component: () => import('../views/tabbar/tabbar.vue'),
        children: [{
          //外卖页
          path: '/msite',
          name: 'msite',
          component: () => import('../views/msite/msite.vue')
        }, {
          //搜索页
          path: '/search/:geohash',
          name: 'search',
          component: () => import('../views/search/search.vue')
        }, {
          //订单页
          path: '/order',
          name: 'order',
          component: () => import('../views/order/order.vue')
        }, {
          //购买商品
          path: '/order/shopgoods',
          name: 'shopgoods',
          component: () => import('../views/order/children/shopgoods.vue')
        }, {
          //我的页
          path: '/profile',
          name: 'profile',
          component: () => import('../views/profile/profile.vue')
        },
        {
          path: '/profile/modify',
          name: 'modify',
          component: () => import('../views/profile/children/modify.vue'),
          meta: {
            title: '修改信息',
            login: true
          }
        }
        ]
      },
      {
        path: '/shop',
        name: 'shop',
        component: () => import('../views/shop/shop.vue')
      },
      {
        path: '/food',
        name: 'food',
        component: () => import('../views/food/food.vue')
      },
      {
        path: '/login',
        name: 'login',
        component: () => import('../views/login/login.vue')
      }
    ]
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '饿了么'
  if (to.name == 'login') {
    //去登录页直接放行
    if (store.state.isLogin) {
      return next({ path: '/msite', replace: true })
    }
    return next()
  }
  const user = store.state.user;
  if (!user && to.meta.login) { //如果没登录，并且需要登录的页面
    return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  next()
})

export default router
